//
//  User.m
//  UniverseProject
//
//  Created by king on 2019/9/3.
//  Copyright © 2019年 Cloud2209. All rights reserved.
//

//定时器周期(秒)/// 业务要求每5分钟请求刷新token请求
static int const TIMER_PERIOD_SECOND = 300;

#import "LoginC.h"
#import "BONaviViewController.h"
#import "User.h"


@implementation UserToken

@end


@implementation User
SingletonM(User)


/// 判断是否登录
+ (BOOL)isLogin{
    
    return YES;
}


/// 退出登录
+ (void)quitLogin{
    
    [self pauseTokenTimer];
}


+ (void)modalToLoginC{
    BONaviViewController *nav = [[BONaviViewController alloc] initWithRootViewController:[LoginC new]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
}



#pragma mark - token处理
//创建定时器
+ (void)createTimerToRefreshToken{
    //1.获得定时器对象
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(autoRefreshTokenDataRequest) userInfo:nil repeats:YES];
    //2.还需要添加到runloop
    //标记模式(并不是真正意义的运行模式  标记 == NSDefaultRunLoopMode + UITrackingRunLoopMode)
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [User sharedUser].timer = timer;
}


/// 暂停定时器
+ (void)pauseTokenTimer{
    [[User sharedUser].timer setFireDate:[NSDate distantFuture]];
}

+ (void)continueTimer{
    [[User sharedUser].timer setFireDate:[NSDate date]];
}



/*   自动刷新token接口
    "Result":{
         "token":"鉴权token",
         "refresh_token":"刷新鉴权token"
     }
 */
+ (void)autoRefreshTokenDataRequest{
//    NSLog(@"task----%@--%@--%ld",[NSThread currentThread],[NSRunLoop currentRunLoop].currentMode,count++);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *request_url = @"/U/AC/TOKEN/V1/REFRESH";
    params[@"refresh_token"] = [LGCache getStringRecordByKey:REFRESH_TOKEN];
    [LGAFNetWork POST:request_url params:params success:^(NSURLSessionDataTask *task, ReqSuccessInfo *data) {
        UserToken *user_token = [UserToken mj_objectWithKeyValues:data.Result];
        [LGCache saveStringRecord:user_token.token ByKey:CURRENT_TOKEN];
        [LGCache saveStringRecord:user_token.refresh_token ByKey:REFRESH_TOKEN];
    } fail:^(NSURLSessionDataTask *task, ReqErrorInfo *error) {
        //如果失败,退出到登录页
        [self quitLogin];
        [MBProgressHUD showTipMessageInView:error.Error];
    }];
}



@end
